<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\OverSeasIn;

use App\Models\Basics\SysPlat;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\OverSeasIn\DeliveryBox;
use App\Models\OverSeasIn\DeliveryBoxDetail;
use App\Models\OverSeasIn\DeliveryLogistics;
use Illuminate\Support\Facades\DB;
class DropshippingReceiveAjax {

    /**
     * 入库
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchReceive($param){
        try{
            DB::beginTransaction();
            $dealAt = date('Y-m-d H:i:s');
            $exist = [];
            $deliveryNoExist = [];
            foreach ($param as $item){
                if(in_array($item['detail_key'],$exist)){
                    continue;
                }else{
                    $exist[] = $item['detail_key'];
                }
                list($deliveryNo,$boxNo) = explode('_',$item['detail_key']);
                if(!in_array($deliveryNo,$deliveryNoExist)){
                    $deliveryNoExist[] = $deliveryNo;
                    DeliveryLogistics::query()->updateOrCreate(['delivery_no' => $deliveryNo], ['arrived_at' => $dealAt]);
                }
                $deliveryBoxes = DeliveryBox::query()
                    ->where('delivery_no',$deliveryNo)
                    ->where('box_no',$boxNo)
                    ->get();
                foreach ($deliveryBoxes as $deliveryBox){
                    $total = $deliveryBox->total;
                    $storageTotal = $deliveryBox->storage_total;
                    $thisStorageTotal = min($total - $storageTotal,$item['this_storage_num']);
                    $deliveryBox->storage_total += $thisStorageTotal;
                    if($deliveryBox->storage_total > 0){
                        if($total == $deliveryBox->storage_total){
                            $deliveryBox->status = 3;
                        }else{
                            $deliveryBox->status = 2;
                        }
                    }
                    $deliveryBox->save();

                    //更新装箱明细
                    DeliveryBoxDetail::_upBoxDetail($deliveryBox->id,$total,$storageTotal,$thisStorageTotal,$dealAt,2);

                    //更新库存FnSku数量 (海外仓&一件代发库存)
                    $num = $thisStorageTotal * $deliveryBox->num_per_box;
                    DropshippingInventoryFnsku::_upInventoryBoxFnSku($deliveryBox->warehouse_id,$deliveryBox->account_id,$deliveryBox->fnsku,$deliveryBox->psku_id,$num,$deliveryBox->plat_id);
                }
            }
            DB::commit();
            return response()->json(['status' => true,'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

}
